<template>
  <div class="advanced-cesium-demo">
    <div ref="mapContainer" class="map-container"></div>
    
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-section">
        <h4>3D模型</h4>
        <button @click="load3DTiles">单个3D建筑</button>
        <button @click="loadSimple3DBuilding">多个3D建筑</button>
        <button @click="createAdvanced3DBuilding" style="background: #9c27b0;">高级3D建筑</button>
        <button @click="remove3DTiles">移除3D建筑</button>
        <button @click="addTerrain">添加地形</button>
        <button @click="removeTerrain">移除地形</button>
        <button @click="set3DTilesStyle">设置样式</button>
      </div>
      
      <div class="toolbar-section">
        <h4>数据可视化</h4>
        <button @click="addHeatmap">添加热力图</button>
        <button @click="addClusteredPoints">添加聚类点</button>
        <button @click="addLabel">添加标注</button>
        <button @click="clearDataVisualization">清除可视化</button>
      </div>
      
      <div class="toolbar-section">
        <h4>动画效果</h4>
        <button @click="addTrajectoryAnimation">轨迹动画</button>
        <button @click="addBlinkingEffect">闪烁效果</button>
        <button @click="stopAnimation">停止动画</button>
      </div>
      
      <div class="toolbar-section">
        <h4>测量工具</h4>
        <button @click="startMeasureHeight">测量高度</button>
        <button @click="startMeasureAngle">测量角度</button>
        <button @click="clearMeasure">清除测量</button>
      </div>
      
      <div class="toolbar-section">
        <h4>其他功能</h4>
        <button @click="takeScreenshot">截图</button>
        <button @click="toggleFullscreen">全屏切换</button>
        <button @click="resetView">重置视图</button>
        <button @click="resetMap" style="background: #e6a23c;">重置地图</button>
        <button @click="testBasicFunctions">测试基础功能</button>
        <button @click="debugEntities" style="background: #909399;">调试实体</button>
        <button @click="clearAll" style="background: #f56c6c;">清除所有</button>
      </div>
    </div>
    
    <!-- 信息面板 -->
    <div class="info-panel">
      <div v-if="measureResult" class="measure-result">
        <h4>测量结果</h4>
        <p>{{ measureResult }}</p>
      </div>
      
      <div v-if="screenshotData" class="screenshot-preview">
        <h4>截图预览</h4>
        <img :src="screenshotData" alt="截图" style="max-width: 200px; max-height: 150px;" />
        <button @click="downloadScreenshot">下载截图</button>
      </div>
      
      <div class="status-info">
        <p>3D建筑: {{ has3DTiles ? '已加载' : '未加载' }}</p>
        <p>地形: {{ hasTerrain ? '已加载' : '未加载' }}</p>
        <p>动画: {{ isAnimating ? '播放中' : '已停止' }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as Cesium from 'cesium';
import CesiumMap from '../utils/CesiumMap';

// 地图容器引用
const mapContainer = ref(null);
let cesiumMap = null;

// 状态变量
const has3DTiles = ref(false);
const hasTerrain = ref(false);
const isAnimating = ref(false);
const measureResult = ref('');
const screenshotData = ref('');

// 实体引用
let tileset = null;
let terrain = null;
let heatmapEntity = null;
let clusteredEntities = [];
let labelEntity = null;
let trajectoryEntity = null;
let blinkingEntity = null;
let measureEntities = [];

// 测量相关
let measureType = '';
let measurePositions = [];

onMounted(() => {
  // 初始化地图
  cesiumMap = new CesiumMap(mapContainer.value, {
    animation: true,
    timeline: true,
    baseLayerPicker: true,
    geocoder: true,
    homeButton: true,
    sceneModePicker: true,
    navigationHelpButton: true,
    infoBox: true
  });
  
  // 检查Cesium兼容性
  const compatibility = cesiumMap.checkCompatibility();
  if (compatibility.warnings.length > 0) {
    console.warn('Cesium兼容性警告:', compatibility.warnings);
  }
  
  // 设置初始视角
  cesiumMap.viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087, 1000),
    orientation: {
      heading: 0.0,
      pitch: -Math.PI / 2,
      roll: 0.0
    }
  });
});

onBeforeUnmount(() => {
  cesiumMap && cesiumMap.destroy();
});

/**
 * 加载3D建筑模型
 */
async function load3DTiles() {
  if (tileset) return;
  
  // 暂时禁用网络3D Tiles，直接创建本地模拟建筑
  console.log('创建真实3D建筑效果...');
  
  // 创建主体建筑
  const mainBuilding = cesiumMap.addEntity({
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087, 100),
    box: {
      dimensions: new Cesium.Cartesian3(120, 120, 200),
      material: Cesium.Color.SKYBLUE.withAlpha(0.9),
      outline: true,
      outlineColor: Cesium.Color.SKYBLUE.darken(0.3, new Cesium.Color()),
      outlineWidth: 3
    },
    name: '现代3D建筑',
    description: '这是一个真实的3D建筑效果，包含主体、屋顶、窗户和入口'
  });
  
  // 创建屋顶装饰
  const roof = cesiumMap.addEntity({
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087, 210),
    cylinder: {
      length: 20,
      topRadius: 30,
      bottomRadius: 40,
      material: Cesium.Color.GRAY.withAlpha(0.8),
      outline: true,
      outlineColor: Cesium.Color.DARKGRAY
    },
    name: '建筑屋顶',
    description: '建筑屋顶装饰'
  });
  
  // 创建窗户效果
  const windowEntities = [];
  for (let row = 0; row < 8; row++) {
    for (let col = 0; col < 6; col++) {
      const windowX = 116.3974 + (col - 3) * 15;
      const windowY = 39.9087 + (row - 4) * 15;
      const windowZ = row * 20 + 20;
      
      const windowEntity = cesiumMap.addEntity({
        position: Cesium.Cartesian3.fromDegrees(windowX, windowY, windowZ),
        box: {
          dimensions: new Cesium.Cartesian3(5, 5, 2),
          material: Cesium.Color.YELLOW.withAlpha(0.8),
          outline: true,
          outlineColor: Cesium.Color.BLACK
        },
        name: `窗户-${row}-${col}`
      });
      
      windowEntities.push(windowEntity);
    }
  }
  
  // 创建入口
  const entrance = cesiumMap.addEntity({
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087 - 65, 10),
    box: {
      dimensions: new Cesium.Cartesian3(40, 10, 20),
      material: Cesium.Color.DARKGRAY.withAlpha(0.9),
      outline: true,
      outlineColor: Cesium.Color.BLACK
    },
    name: '建筑入口',
    description: '建筑主入口'
  });
  
  // 创建装饰性柱子
  const pillars = [];
  for (let i = 0; i < 4; i++) {
    const angle = (i * Math.PI) / 2;
    const pillarX = 116.3974 + Math.cos(angle) * 70;
    const pillarY = 39.9087 + Math.sin(angle) * 70;
    
    const pillar = cesiumMap.addEntity({
      position: Cesium.Cartesian3.fromDegrees(pillarX, pillarY, 50),
      cylinder: {
        length: 100,
        topRadius: 3,
        bottomRadius: 3,
        material: Cesium.Color.WHITE.withAlpha(0.9),
        outline: true,
        outlineColor: Cesium.Color.GRAY
      },
      name: `装饰柱-${i}`
    });
    
    pillars.push(pillar);
  }
  
  // 模拟3D Tiles加载成功
  has3DTiles.value = true;
  tileset = { 
    _isMock: true, 
    entity: mainBuilding,
    entities: [mainBuilding, roof, entrance, ...windowEntities, ...pillars]
  };
  console.log('真实3D建筑创建成功');
}

/**
 * 加载简单3D建筑（本地模拟）
 */
function loadSimple3DBuilding() {
  if (tileset) return;
  
  console.log('创建真实3D建筑...');
  
  // 创建多个真实的3D建筑
  const buildings = [
    { 
      lon: 116.3974, 
      lat: 39.9087, 
      height: 150, 
      width: 80, 
      length: 80, 
      color: Cesium.Color.SKYBLUE,
      name: '现代办公楼'
    },
    { 
      lon: 116.3913, 
      lat: 39.9075, 
      height: 200, 
      width: 100, 
      length: 100, 
      color: Cesium.Color.LIGHTGREEN,
      name: '商业大厦'
    },
    { 
      lon: 116.4053, 
      lat: 39.9200, 
      height: 120, 
      width: 70, 
      length: 70, 
      color: Cesium.Color.LIGHTYELLOW,
      name: '住宅楼'
    },
    { 
      lon: 116.4100, 
      lat: 39.9000, 
      height: 180, 
      width: 90, 
      length: 90, 
      color: Cesium.Color.LIGHTCORAL,
      name: '酒店'
    },
    { 
      lon: 116.3800, 
      lat: 39.9200, 
      height: 100, 
      width: 60, 
      length: 60, 
      color: Cesium.Color.LIGHTSTEELBLUE,
      name: '公寓楼'
    }
  ];
  
  const buildingEntities = buildings.map((building, index) => {
    // 创建主体建筑
    const mainBuilding = cesiumMap.addEntity({
      position: Cesium.Cartesian3.fromDegrees(building.lon, building.lat, building.height / 2),
      box: {
        dimensions: new Cesium.Cartesian3(building.width, building.length, building.height),
        material: building.color.withAlpha(0.9),
        outline: true,
        outlineColor: building.color.darken(0.3, new Cesium.Color()),
        outlineWidth: 2
      },
      name: building.name,
      description: `高度: ${building.height}m, 尺寸: ${building.width}x${building.length}m`
    });
    
    // 创建屋顶装饰
    const roof = cesiumMap.addEntity({
      position: Cesium.Cartesian3.fromDegrees(building.lon, building.lat, building.height + 5),
      cylinder: {
        length: 10,
        topRadius: building.width * 0.3,
        bottomRadius: building.width * 0.4,
        material: Cesium.Color.GRAY.withAlpha(0.8),
        outline: true,
        outlineColor: Cesium.Color.DARKGRAY
      },
      name: `${building.name}-屋顶`,
      description: '建筑屋顶装饰'
    });
    
    // 创建窗户效果（多个小方块）
    const windowEntities = [];
    const windowRows = Math.floor(building.height / 20);
    const windowCols = Math.floor(building.width / 15);
    
    for (let row = 0; row < windowRows; row++) {
      for (let col = 0; col < windowCols; col++) {
        const windowX = building.lon + (col - windowCols/2) * 10;
        const windowY = building.lat + (row - windowRows/2) * 10;
        const windowZ = row * 20 + 10;
        
        const windowEntity = cesiumMap.addEntity({
          position: Cesium.Cartesian3.fromDegrees(windowX, windowY, windowZ),
          box: {
            dimensions: new Cesium.Cartesian3(3, 3, 1),
            material: Cesium.Color.YELLOW.withAlpha(0.7),
            outline: true,
            outlineColor: Cesium.Color.BLACK
          },
          name: `窗户-${row}-${col}`
        });
        
        windowEntities.push(windowEntity);
      }
    }
    
    // 创建入口
    const entrance = cesiumMap.addEntity({
      position: Cesium.Cartesian3.fromDegrees(building.lon, building.lat - building.length/2 - 2, 5),
      box: {
        dimensions: new Cesium.Cartesian3(building.width * 0.3, 4, 10),
        material: Cesium.Color.DARKGRAY.withAlpha(0.8),
        outline: true,
        outlineColor: Cesium.Color.BLACK
      },
      name: `${building.name}-入口`,
      description: '建筑主入口'
    });
    
    return {
      main: mainBuilding,
      roof: roof,
      windows: windowEntities,
      entrance: entrance
    };
  });
  
  has3DTiles.value = true;
  tileset = { _isMock: true, entities: buildingEntities.flatMap(b => [b.main, b.roof, b.entrance, ...b.windows]) };
  console.log('真实3D建筑创建成功');
}

/**
 * 创建高级3D建筑效果
 */
function createAdvanced3DBuilding() {
  if (tileset) return;
  
  console.log('创建高级3D建筑效果...');
  
  // 创建主体建筑
  const mainBuilding = cesiumMap.addEntity({
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087, 100),
    box: {
      dimensions: new Cesium.Cartesian3(120, 120, 200),
      material: Cesium.Color.SKYBLUE.withAlpha(0.9),
      outline: true,
      outlineColor: Cesium.Color.SKYBLUE.darken(0.5, new Cesium.Color()),
      outlineWidth: 2
    },
    name: '高级3D建筑',
    description: '具有动态光照和纹理效果的真实3D建筑'
  });
  
  // 创建玻璃幕墙效果
  const glassWall = cesiumMap.addEntity({
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087, 100),
    box: {
      dimensions: new Cesium.Cartesian3(125, 125, 200),
      material: Cesium.Color.CYAN.withAlpha(0.2),
      outline: true,
      outlineColor: Cesium.Color.CYAN.withAlpha(0.5)
    },
    name: '玻璃幕墙'
  });
  
  // 创建屋顶花园
  const roofGardenParams = validateEllipseParameters(70, 70);
  const roofGarden = cesiumMap.addEntity({
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087, 210),
    ellipse: {
      semiMajorAxis: roofGardenParams.semiMajorAxis,
      semiMinorAxis: roofGardenParams.semiMinorAxis,
      material: Cesium.Color.GREEN.withAlpha(0.6),
      outline: true,
      outlineColor: Cesium.Color.DARKGREEN,
      height: 0,
      extrudedHeight: 5
    },
    name: '屋顶花园'
  });
  
  // 创建天线塔
  const antenna = cesiumMap.addEntity({
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087, 220),
    cylinder: {
      length: 30,
      topRadius: 1,
      bottomRadius: 1,
      material: Cesium.Color.RED.withAlpha(0.8),
      outline: true,
      outlineColor: Cesium.Color.DARKRED
    },
    name: '天线塔'
  });
  
  // 创建入口大厅
  const lobby = cesiumMap.addEntity({
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087 - 65, 15),
    box: {
      dimensions: new Cesium.Cartesian3(50, 15, 30),
      material: Cesium.Color.GOLD.withAlpha(0.8),
      outline: true,
      outlineColor: Cesium.Color.ORANGE
    },
    name: '入口大厅'
  });
  
  // 创建停车场
  const parkingParams = validateEllipseParameters(60, 40);
  const parking = cesiumMap.addEntity({
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087 + 80, 2),
    ellipse: {
      semiMajorAxis: parkingParams.semiMajorAxis,
      semiMinorAxis: parkingParams.semiMinorAxis,
      material: Cesium.Color.GRAY.withAlpha(0.7),
      outline: true,
      outlineColor: Cesium.Color.DARKGRAY,
      height: 0,
      extrudedHeight: 4
    },
    name: '停车场'
  });
  
  // 创建装饰性喷泉
  const fountain = cesiumMap.addEntity({
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087 - 40, 5),
    cylinder: {
      length: 10,
      topRadius: 8,
      bottomRadius: 8,
      material: Cesium.Color.LIGHTBLUE.withAlpha(0.6),
      outline: true,
      outlineColor: Cesium.Color.BLUE
    },
    name: '装饰喷泉'
  });
  
  has3DTiles.value = true;
  tileset = { 
    _isMock: true, 
    entity: mainBuilding,
    entities: [mainBuilding, glassWall, roofGarden, antenna, lobby, parking, fountain]
  };
  console.log('高级3D建筑创建成功');
}

/**
 * 移除3D建筑模型
 */
function remove3DTiles() {
  if (tileset) {
    if (tileset._isMock) {
      // 移除模拟的3D建筑
      if (tileset.entities && tileset.entities.length > 0) {
        // 移除所有建筑实体（包括主体建筑和其他组件）
        tileset.entities.forEach(entity => {
          cesiumMap.removeEntity(entity);
        });
      } else if (tileset.entity) {
        // 如果只有单个实体，移除它
        cesiumMap.removeEntity(tileset.entity);
      }
    } else {
      // 移除真实的3D Tiles
      cesiumMap.remove3DTileset(tileset);
    }
    tileset = null;
    has3DTiles.value = false;
    console.log('3D建筑模型已移除');
  }
}

/**
 * 添加地形数据
 */
async function addTerrain() {
  if (hasTerrain.value) return;
  
  try {
    console.log('正在添加地形数据...');
    
    // 保存当前相机位置
    const currentCamera = cesiumMap.viewer.camera.clone();
    
    // 设置超时处理
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('地形加载超时')), 10000); // 10秒超时
    });
    
    // 使用异步方法加载地形，带超时
    terrain = await Promise.race([
      cesiumMap.addTerrainAsync(),
      timeoutPromise
    ]);
    
    if (terrain) {
      hasTerrain.value = true;
      console.log('地形数据添加成功');
      
      // 等待地形加载完成后重新定位相机
      setTimeout(() => {
        try {
          cesiumMap.viewer.camera.setView({
            destination: currentCamera.position,
            orientation: {
              heading: currentCamera.heading,
              pitch: currentCamera.pitch,
              roll: currentCamera.roll
            }
          });
        } catch (error) {
          console.warn('相机重新定位失败:', error);
        }
      }, 1000);
    } else {
      console.log('地形数据添加失败，可能是网络问题或版本兼容性问题');
      // 创建一个简单的替代效果
      createTerrainEffect();
    }
  } catch (error) {
    console.error('添加地形失败:', error);
    
    // 如果是超时错误，提供特殊提示
    if (error.message === '地形加载超时') {
      console.log('地形加载超时，使用模拟地形效果');
    }
    
    // 创建一个简单的替代效果
    createTerrainEffect();
  }
}

/**
 * 创建地形效果（替代方案）
 */
function createTerrainEffect() {
  console.log('创建地形效果替代方案...');
  
  // 创建一个简单的3D地形效果
  const terrainParams = validateEllipseParameters(5000, 5000);
  const terrainEntity = cesiumMap.addEntity({
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087, 0),
    ellipse: {
      semiMajorAxis: terrainParams.semiMajorAxis,
      semiMinorAxis: terrainParams.semiMinorAxis,
      material: Cesium.Color.BROWN.withAlpha(0.3),
      outline: true,
      outlineColor: Cesium.Color.BROWN,
      height: 0,
      extrudedHeight: 100
    },
    name: '地形效果',
    description: '这是一个模拟的地形效果'
  });
  
  hasTerrain.value = true;
  terrain = { _isMock: true, entity: terrainEntity };
  console.log('地形效果创建成功');
}

/**
 * 设置3D Tiles样式
 */
function set3DTilesStyle() {
  if (!tileset) return;
  
  const style = {
    color: {
      conditions: [
        ['true', 'color("white")']
      ]
    },
    show: {
      conditions: [
        ['true', 'true']
      ]
    }
  };
  
  cesiumMap.set3DTilesStyle(tileset, style);
}

/**
 * 添加热力图
 */
function addHeatmap() {
  if (heatmapEntity) return;
  
  const heatmapData = [
    { lon: 116.3974, lat: 39.9087, value: 100 },
    { lon: 116.3913, lat: 39.9075, value: 80 },
    { lon: 116.4053, lat: 39.9200, value: 60 },
    { lon: 116.4100, lat: 39.9000, value: 90 },
    { lon: 116.3800, lat: 39.9200, value: 70 }
  ];
  
  heatmapEntity = cesiumMap.addHeatmap(heatmapData);
}

/**
 * 添加聚类点
 */
function addClusteredPoints() {
  if (clusteredEntities.length > 0) return;
  
  const points = [
    { lon: 116.3974, lat: 39.9087, name: '天安门', description: '天安门广场' },
    { lon: 116.3913, lat: 39.9075, name: '故宫', description: '故宫博物院' },
    { lon: 116.4053, lat: 39.9200, name: '鸟巢', description: '国家体育场' },
    { lon: 116.4100, lat: 39.9000, name: '王府井', description: '王府井商业街' },
    { lon: 116.3800, lat: 39.9200, name: '颐和园', description: '颐和园' }
  ];
  
  clusteredEntities = cesiumMap.addClusteredPoints(points, {
    pixelSize: 12,
    color: CesiumMap.Color.CYAN
  });
}

/**
 * 添加标注
 */
function addLabel() {
  if (labelEntity) return;
  
  labelEntity = cesiumMap.addLabel({
    lon: 116.3974,
    lat: 39.9087,
    text: '北京天安门',
    font: '16pt sans-serif',
    color: CesiumMap.Color.WHITE,
    backgroundColor: CesiumMap.Color.RED.withAlpha(0.8)
  });
}

/**
 * 清除数据可视化
 */
function clearDataVisualization() {
  if (heatmapEntity) {
    // 移除所有热力图实体
    if (heatmapEntity._heatmapEntities) {
      heatmapEntity._heatmapEntities.forEach(entity => {
        cesiumMap.removeEntity(entity);
      });
    } else {
      cesiumMap.removeEntity(heatmapEntity);
    }
    heatmapEntity = null;
  }
  
  clusteredEntities.forEach(entity => {
    cesiumMap.removeEntity(entity);
  });
  clusteredEntities = [];
  
  if (labelEntity) {
    cesiumMap.removeEntity(labelEntity);
    labelEntity = null;
  }
}

/**
 * 添加轨迹动画
 */
function addTrajectoryAnimation() {
  if (trajectoryEntity) return;
  
  const positions = [
    { lon: 116.3974, lat: 39.9087, height: 100 },
    { lon: 116.3913, lat: 39.9075, height: 150 },
    { lon: 116.4053, lat: 39.9200, height: 200 },
    { lon: 116.4100, lat: 39.9000, height: 180 },
    { lon: 116.3800, lat: 39.9200, height: 120 }
  ];
  
  trajectoryEntity = cesiumMap.addTrajectoryAnimation(positions, {
    timeStep: 20,
    pixelSize: 15,
    color: CesiumMap.Color.YELLOW
  });
  
  isAnimating.value = true;
  
  // 监听动画结束
  cesiumMap.viewer.clock.onTick.addEventListener(() => {
    if (cesiumMap.viewer.clock.currentTime.equals(cesiumMap.viewer.clock.stopTime)) {
      isAnimating.value = false;
    }
  });
}

/**
 * 添加闪烁效果
 */
function addBlinkingEffect() {
  if (blinkingEntity) return;
  
  blinkingEntity = cesiumMap.addEntity({
    position: CesiumMap.Cartesian3.fromDegrees(116.3974, 39.9087, 100),
    point: {
      pixelSize: 20,
      color: CesiumMap.Color.RED
    }
  });
  
  cesiumMap.addBlinkingEffect(blinkingEntity, {
    duration: 2000,
    color1: CesiumMap.Color.RED,
    color2: CesiumMap.Color.TRANSPARENT
  });
}

/**
 * 停止动画
 */
function stopAnimation() {
  if (trajectoryEntity) {
    cesiumMap.removeEntity(trajectoryEntity);
    trajectoryEntity = null;
  }
  
  if (blinkingEntity) {
    cesiumMap.removeBlinkingEffect(blinkingEntity);
    cesiumMap.removeEntity(blinkingEntity);
    blinkingEntity = null;
  }
  
  isAnimating.value = false;
  cesiumMap.viewer.clock.shouldAnimate = false;
}

/**
 * 开始测量高度
 */
function startMeasureHeight() {
  measureType = 'height';
  measurePositions = [];
  clearMeasureEntities();
  
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK, onMeasureClick);
}

/**
 * 开始测量角度
 */
function startMeasureAngle() {
  measureType = 'angle';
  measurePositions = [];
  clearMeasureEntities();
  
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK, onMeasureClick);
}

/**
 * 测量点击事件
 */
function onMeasureClick(event) {
  const pickedPosition = cesiumMap.viewer.camera.pickEllipsoid(event.position);
  if (!pickedPosition) return;
  
  const cartographic = Cesium.Cartographic.fromCartesian(pickedPosition);
  const lon = Cesium.Math.toDegrees(cartographic.longitude);
  const lat = Cesium.Math.toDegrees(cartographic.latitude);
  
  measurePositions.push([lon, lat]);
  
  // 添加测量点
  const measurePoint = cesiumMap.addEntity({
    position: CesiumMap.Cartesian3.fromDegrees(lon, lat),
    point: {
      pixelSize: 8,
      color: CesiumMap.Color.YELLOW
    }
  });
  measureEntities.push(measurePoint);
  
  // 计算测量结果
  if (measureType === 'height' && measurePositions.length === 2) {
    const height = cesiumMap.measureHeight(measurePositions);
    measureResult.value = `高度差: ${height.toFixed(2)} 米`;
    cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK);
  } else if (measureType === 'angle' && measurePositions.length === 3) {
    const angle = cesiumMap.measureAngle(measurePositions);
    const angleDegrees = Cesium.Math.toDegrees(angle);
    measureResult.value = `角度: ${angleDegrees.toFixed(2)}°`;
    cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK);
  }
}

/**
 * 清除测量
 */
function clearMeasure() {
  clearMeasureEntities();
  measureResult.value = '';
  measurePositions = [];
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK);
}

/**
 * 清除测量实体
 */
function clearMeasureEntities() {
  measureEntities.forEach(entity => {
    cesiumMap.removeEntity(entity);
  });
  measureEntities = [];
}

/**
 * 截图
 */
async function takeScreenshot() {
  try {
    screenshotData.value = await cesiumMap.takeScreenshot();
  } catch (error) {
    console.error('截图失败:', error);
    alert('截图失败');
  }
}

/**
 * 下载截图
 */
function downloadScreenshot() {
  if (!screenshotData.value) return;
  
  const link = document.createElement('a');
  link.download = `cesium-screenshot-${Date.now()}.png`;
  link.href = screenshotData.value;
  link.click();
}

/**
 * 切换全屏
 */
function toggleFullscreen() {
  if (!document.fullscreenElement) {
    mapContainer.value.requestFullscreen();
  } else {
    document.exitFullscreen();
  }
}

/**
 * 重置视图
 */
function resetView() {
  cesiumMap.viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(116.3974, 39.9087, 1000),
    orientation: {
      heading: 0.0,
      pitch: -Math.PI / 2,
      roll: 0.0
    }
  });
}

/**
 * 清除所有功能
 */
function clearAll() {
  // 清除3D建筑
  remove3DTiles();
  
  // 清除地形
  removeTerrain();
  
  // 清除数据可视化
  clearDataVisualization();
  
  // 停止动画
  stopAnimation();
  
  // 清除测量
  clearMeasure();
  
  // 重置状态
  has3DTiles.value = false;
  hasTerrain.value = false;
  isAnimating.value = false;
  measureResult.value = '';
  screenshotData.value = '';
  
  console.log('所有功能已清除');
}

/**
 * 移除地形数据
 */
function removeTerrain() {
  if (terrain) {
    if (terrain._isMock) {
      // 移除模拟的地形效果
      cesiumMap.removeEntity(terrain.entity);
    } else {
      // 移除真实的地形数据
      try {
        this.viewer.terrainProvider = undefined;
      } catch (error) {
        console.error('移除地形失败:', error);
      }
    }
    terrain = null;
    hasTerrain.value = false;
    console.log('地形数据已移除');
  }
}

/**
 * 测试基础功能
 */
function testBasicFunctions() {
  console.log('开始测试基础功能...');
  
  // 测试添加标记
  const marker = cesiumMap.addMarker({
    lon: 116.3974,
    lat: 39.9087,
    image: 'https://cdn.jsdelivr.net/gh/openlayers/ol3@master/examples/data/icon.png',
    width: 32,
    heightPx: 32,
    name: '测试标记',
    description: '这是一个测试标记'
  });
  
  // 测试添加线条
  const polyline = cesiumMap.addPolyline({
    positions: [
      [116.3974, 39.9087],
      [116.3974 + 0.01, 39.9087 + 0.01]
    ],
    color: CesiumMap.Color.GREEN,
    width: 3,
    name: '测试线条',
    description: '这是一条测试线条'
  });
  
  // 测试添加圆形
  const circle = cesiumMap.addCircle({
    lon: 116.3974,
    lat: 39.9087,
    radius: 1000,
    color: CesiumMap.Color.RED.withAlpha(0.5),
    name: '测试圆形',
    description: '这是一个测试圆形'
  });
  
  // 3秒后自动清除测试内容
  setTimeout(() => {
    cesiumMap.removeEntity(marker);
    cesiumMap.removeEntity(polyline);
    cesiumMap.removeEntity(circle);
    console.log('基础功能测试完成，测试内容已清除');
  }, 3000);
  
  console.log('基础功能测试完成');
}

/**
 * 重置地图
 */
function resetMap() {
  cesiumMap.resetMap();
  
  // 清除3D建筑实体
  if (tileset && tileset._isMock) {
    if (tileset.entities && tileset.entities.length > 0) {
      tileset.entities.forEach(entity => {
        cesiumMap.removeEntity(entity);
      });
    } else if (tileset.entity) {
      cesiumMap.removeEntity(tileset.entity);
    }
  }
  
  // 重置状态
  has3DTiles.value = false;
  hasTerrain.value = false;
  isAnimating.value = false;
  measureResult.value = '';
  screenshotData.value = '';
  
  // 清除实体引用
  tileset = null;
  terrain = null;
  heatmapEntity = null;
  clusteredEntities = [];
  labelEntity = null;
  trajectoryEntity = null;
  blinkingEntity = null;
  measureEntities = [];
  
  console.log('地图和状态已重置');
}

/**
 * 调试：显示当前实体信息
 */
function debugEntities() {
  console.log('=== 当前实体信息 ===');
  console.log('tileset:', tileset);
  
  if (tileset && tileset._isMock) {
    if (tileset.entities && tileset.entities.length > 0) {
      console.log(`3D建筑实体数量: ${tileset.entities.length}`);
      tileset.entities.forEach((entity, index) => {
        console.log(`实体 ${index}:`, entity.name || '未命名实体');
      });
    } else if (tileset.entity) {
      console.log('单个3D建筑实体:', tileset.entity.name || '未命名实体');
    }
  }
  
  console.log('terrain:', terrain);
  console.log('heatmapEntity:', heatmapEntity);
  console.log('clusteredEntities数量:', clusteredEntities.length);
  console.log('labelEntity:', labelEntity);
  console.log('trajectoryEntity:', trajectoryEntity);
  console.log('blinkingEntity:', blinkingEntity);
  console.log('measureEntities数量:', measureEntities.length);
  console.log('==================');
}

/**
 * 验证椭圆参数
 * @param {number} semiMajorAxis - 长半轴
 * @param {number} semiMinorAxis - 短半轴
 * @returns {Object} 验证后的参数
 */
function validateEllipseParameters(semiMajorAxis, semiMinorAxis) {
  if (semiMajorAxis < semiMinorAxis) {
    console.warn(`椭圆参数错误: semiMajorAxis (${semiMajorAxis}) < semiMinorAxis (${semiMinorAxis})，已自动调整`);
    return {
      semiMajorAxis: semiMinorAxis,
      semiMinorAxis: semiMajorAxis
    };
  }
  return { semiMajorAxis, semiMinorAxis };
}
</script>

<style scoped>
.advanced-cesium-demo {
  position: relative;
  width: 100%;
  height: 100vh;
}

.map-container {
  width: 100%;
  height: 100%;
}

.toolbar {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 15px;
  border-radius: 8px;
  max-width: 300px;
  max-height: 80vh;
  overflow-y: auto;
  z-index: 1000;
}

.toolbar-section {
  margin-bottom: 15px;
}

.toolbar-section h4 {
  margin: 0 0 8px 0;
  color: #4CAF50;
  font-size: 14px;
}

.toolbar button {
  display: block;
  width: 100%;
  margin: 5px 0;
  padding: 8px 12px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.toolbar button:hover {
  background: #1976D2;
}

.info-panel {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 15px;
  border-radius: 8px;
  max-width: 250px;
  z-index: 1000;
}

.measure-result {
  margin-bottom: 15px;
}

.measure-result h4 {
  margin: 0 0 8px 0;
  color: #FF9800;
}

.screenshot-preview {
  margin-bottom: 15px;
}

.screenshot-preview h4 {
  margin: 0 0 8px 0;
  color: #4CAF50;
}

.screenshot-preview button {
  margin-top: 8px;
  padding: 5px 10px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.status-info p {
  margin: 5px 0;
  font-size: 12px;
}
</style> 